package history.hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// 238. 除自身以外数组的乘积:https://leetcode-cn.com/problems/product-of-array-except-self/
public class LeetCode_238 {
    public static void main(String[] args) {
        int test [] = {1,2,0,4};
        productExceptSelf(test);
    }

    public static int[] productExceptSelf(int[] nums) {
        if (nums == null || nums.length<=0) return new int[0];
        if (nums.length == 1) return nums;
        int []result = new int[nums.length];
        int allData = 1;
        for (int i=1;i<nums.length;i++) {
            allData *= nums[i];
        }
        if (allData == 0) {
            List<Integer> zeroIndexList = new ArrayList<>();
            int allDataTemp = 1;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == 0) {
                    zeroIndexList.add(i);
                } else {
                    allDataTemp*=nums[i];
                }
            }
            Arrays.fill(result,0);
            if (zeroIndexList.size()==1) {
              result[zeroIndexList.get(0)] = allDataTemp;
            }
            return result;
            }
        result[0] = allData;
        for (int i=1;i<nums.length;i++) {
            if (nums[i] !=0) result[i] = result[i-1]*nums[i-1]/nums[i];
            else result[i] = allData*nums[i-1];
        }
        return result;
    }
}
